package com.test.demo.nettydemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioChannelOption;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;

public class NettyServer {

    public static void main(String[] args) {
        //接收连接请求
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        //接受其他读写请求
        NioEventLoopGroup workersGroup = new NioEventLoopGroup(8);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();

            serverBootstrap.group(bossGroup, workersGroup)//绑定两个线程
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    System.out.println("执行了回调");
                    socketChannel.pipeline().addLast("decoder",new ByteArrayDecoder());
                    socketChannel.pipeline().addLast("encoder",new ByteArrayEncoder());
                    socketChannel.pipeline().addLast(new HelloServerHandler());
                }
            });
            System.out.println("服务器启动成功");

            ChannelFuture cf = serverBootstrap.bind(9000).sync();
            cf.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workersGroup.shutdownGracefully();
        }
    }
}
